#-*- coding: utf-8 -*-
# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from datetime import datetime
from django import  forms
from iFriends.People.models import Person, Blog
from iFriends.People.views import PersonForm
from iFriends.Quotes.models import Quote
#Insersação de Usuarios
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User, Group
from django.contrib.auth import authenticate, login, logout
from django.template import RequestContext
from django.contrib.auth.decorators import login_required

class EmailForm(forms.Form):
        title = forms.CharField(max_length=50,
                                widget=forms.TextInput(attrs={'size':'50'}))
        sender = forms.EmailField(max_length=30,
                                  widget=forms.TextInput(attrs={'size':'50'}))
        date = forms.DateTimeField()
# Antes era assim
#        text = forms.CharField(max_length=200)
        text = forms.CharField(widget=forms.Textarea(attrs={'rows':'6','cols':'75'}))

def contact_view(request):
    eForm = EmailForm()
    return render_to_response('home/contact_form.html', { 'eForm':eForm })
@login_required
def home_view(request):
    quotes = Quote.objects.all()
    pList = Person.objects.all()
    if request.user.is_authenticated():
        bList = Blog.objects.all()
    else:
        bList = []
    
    return render_to_response('home/homepage.html',
                              {'quotes':quotes, 'pList':pList,
                               'bList':bList},context_instance = RequestContext(request))


gender_list = (('M','Male'),('F','Female'))
class NewUserForm(forms.Form):
    username = forms.CharField(max_length=30)
    password = forms.CharField(max_length=20, widget=forms.PasswordInput())
    first = forms.CharField(max_length=20)
    last = forms.CharField(max_length=20)
    gender = forms.ChoiceField(choices=gender_list)
    email = forms.EmailField(max_length=30)
    

def create_user(request):
    message = 'Create New User'
    uForm = NewUserForm()
    
    if request.method == 'POST':
        if request.POST['submit'] == 'Create':
            postDict = request.POST.copy()
            uForm = NewUserForm(postDict)
            try:
                #Create User Object
                user = User.objects.create_user(postDict['username'],
                                                postDict['email'],
                                                postDict['password'])
                user.last_name = postDict['last']
                user.first_name = postDict['first']
                user.groups.add(Group.objects.get(name='iFriends'))
                user.save()
                
                #Create a Person Object
                perDict = {}
                perDict['name'] = postDict['first']
                perDict['gender'] = postDict['gender']
                perDict['favoriteURL'] = 'http://www.corujadeti.com.br/'
                perDict['email'] = postDict['email']
                perDict['userID'] = user.id
                #SaveForm = forms.form_for_
                pForm = PersonForm(perDict)
                if pForm.is_valid():
                    try:
                        p = pForm.save()
                        return HttpResponseRedirect('/People/Info/%d/' % p.id)
                    except:
                        message = 'Database Error.'
                        user.delete()
                else:
                    message = 'Form Data Error.'
                    user.delete()
            except:
                message = 'Person Creation Error '
    return render_to_response('registration/create_user.html',{'uForm': uForm,'message':message})


class LoginForm(forms.Form):
    username =forms.CharField(max_length=30)
    password= forms.CharField(max_length=20, widget=forms.PasswordInput())
    
def login_user(request, next='/'):
    message = 'Login User'
    lForm = LoginForm()
    
#    if request.GET.has_key('next'): Antes de testar cookies
#        next = request.GET['next']
        
    if request.method == 'GET':
        request.session.set_test_cookie()
        
    if request.method == 'POST':
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            
            if request.GET.has_key('next'):
                next = request.GET['next']
            if request.POST['submit'] == 'Login':        
                postDict = request.POST.copy()
                lForm = LoginForm(postDict)
                if lForm.is_valid():
                    uName = request.POST['username']
                    uPass = request.POST['password']
                    user = authenticate(username=uName,password=uPass)
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            return HttpResponseRedirect(next)
                        else:
                            message = 'Account Deactivated'
                    else:
                        message = 'Login Incorrect'
        else:
            message = "Please enable cookies an try again"
    return render_to_response('registration/login.html',{
                                'lForm':lForm,
                                'message':message})
def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/Login')